package com.example.canvasdemo.ui

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import java.io.ByteArrayOutputStream

class CustomCanvasView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paintList = mutableListOf<Paint>()
    private val pathList = mutableListOf<Path>()

    private var currentPaint = Paint().apply {
        color = Color.BLACK
        strokeWidth = 5f
        style = Paint.Style.STROKE
        isAntiAlias = true
    }
    private var currentPath = Path()
    private var isEraserMode = false

    fun setColor(color: Int) {
        if (!isEraserMode) {
            currentPaint.color = color
        }
    }

    fun setStrokeWidth(width: Float) {
        currentPaint.strokeWidth = width
    }

    fun enableEraserMode() {
        isEraserMode = true
        currentPaint.color = Color.WHITE
    }

    // 禁用橡皮擦模式
    fun disableEraserMode() {
        isEraserMode = false
    }

    // 清空画布
    fun clearCanvas() {
        pathList.clear()
        paintList.clear()
        invalidate()
    }

    fun getDrawingData(): String {
        val bitmap = getBitmapFromCanvas()
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        val byteArray = outputStream.toByteArray()
        return android.util.Base64.encodeToString(byteArray, android.util.Base64.DEFAULT)
    }


    private fun getBitmapFromCanvas(): Bitmap {
        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        draw(canvas) // 调用 onDraw 方法将内容绘制到位图
        return bitmap
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        for (i in pathList.indices) {
            canvas.drawPath(pathList[i], paintList[i])
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x
        val y = event.y
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                currentPath = Path()
                currentPath.moveTo(x, y)
                pathList.add(currentPath)

                val newPaint = Paint(currentPaint)
                paintList.add(newPaint)
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                currentPath.lineTo(x, y)
            }
        }
        invalidate()
        return true
    }
}

